Java进阶-手动使用 throw 抛出异常

自定义“无效名字异常”

  • 编译时异常,直接继承 Exception
  • 运行时异常,直接继承 RuntimeException
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class IllegalNameException extends Exception { // 编译时异常
// public class IllegalNameException extends RuntimeException { // 运行时异常

// 定义异常一般提供两个构造方法
public IllegalNameException() {
}

public IllegalNameException(String msg) {
super(msg);
}
}

public class CustomerService01 {
public void register(String name) throws IllegalNameException {
// 完成注册
if (name.length() < 6) {
// 创建异常对象
// IllegalNameException e = new IllegalNameException("用户名长度不少于6位");

// 手动抛出异常
// throw e;
throw new IllegalNameException("用户名长度不少于6位");
}

// 如果能执行到此,说明用户名合法
System.out.println("注册成功");
}
}

public class Test01 {

public static void main(String[] args) {
String username = "jack";

CustomerService01 cs = new CustomerService01();

try {
cs.register(username);
} catch (IllegalNameException e) {
System.out.println(e.getMessage());
}
}
}